<template>
  <div class="container fade-in">
    <div class="header">
      <div class="breadcrumb">
        <router-link to="/coupons" class="breadcrumb-link">优惠券管理</router-link>
        <span class="breadcrumb-separator">></span>
        <span class="breadcrumb-current">优惠券详情</span>
      </div>
      <div class="actions">
        <button class="btn secondary" @click="$router.back()">
          <span class="icon">←</span>
          返回
        </button>
        <button v-if="template" class="btn primary" @click="editTemplate">
          <span class="icon">✏️</span>
          编辑模板
        </button>
      </div>
    </div>

    <div v-if="loading" class="loading-state">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <div v-else-if="!template" class="error-state">
      <div class="icon">❌</div>
      <h3>优惠券模板不存在</h3>
      <p>该优惠券模板可能已被删除或不存在</p>
      <button class="btn primary" @click="$router.push('/coupons')">返回列表</button>
    </div>

    <div v-else class="content">
      <!-- 模板基本信息 -->
      <div class="card slide-up" style="animation-delay: 0.1s">
        <div class="card-header">
          <h3 class="section-title">模板信息</h3>
          <div class="template-status">
            <span class="status-badge" :class="template.isActive ? 'active' : 'inactive'">
              {{ template.isActive ? '启用' : '禁用' }}
            </span>
          </div>
        </div>
        <div class="template-info">
          <div class="info-grid">
            <div class="info-item">
              <label>模板名称</label>
              <div class="value">{{ template.name }}</div>
            </div>
            <div class="info-item">
              <label>优惠券类型</label>
              <div class="value">
                <span class="badge" :class="getCouponTypeBadgeClass(template.couponType)">
                  {{ getCouponTypeText(template.couponType) }}
                </span>
              </div>
            </div>
            <div class="info-item">
              <label>优惠内容</label>
              <div class="value discount-value">{{ formatCouponValue(template) }}</div>
            </div>
            <div class="info-item">
              <label>使用门槛</label>
              <div class="value">
                {{ template.useThresholdAmount ? formatMoney(template.useThresholdAmount) : '无门槛' }}
              </div>
            </div>
            <div class="info-item">
              <label>有效期</label>
              <div class="value">{{ template.validityPeriod || 0 }} 天</div>
            </div>
            <div class="info-item">
              <label>当前库存</label>
              <div class="value">
                <span class="inventory" :class="getInventoryClass(template.inventory)">
                  {{ template.inventory || 0 }}
                </span>
              </div>
            </div>
            <div class="info-item">
              <label>创建时间</label>
              <div class="value">{{ formatDate(template.createdAt) }}</div>
            </div>
            <div class="info-item">
              <label>更新时间</label>
              <div class="value">{{ formatDate(template.updatedAt) }}</div>
            </div>
          </div>
          <div v-if="template.description" class="description">
            <label>描述</label>
            <div class="value">{{ template.description }}</div>
          </div>
        </div>
      </div>

      <!-- 统计数据 -->
      <div class="grid stats">
        <div class="card stat slide-up" style="animation-delay: 0.2s">
          <div class="icon" style="background: var(--primary)">📊</div>
          <div class="meta">
            <div class="label">总发放量</div>
            <div class="value">{{ stats.totalIssued }}</div>
          </div>
        </div>
        <div class="card stat slide-up" style="animation-delay: 0.3s">
          <div class="icon" style="background: var(--success)">✅</div>
          <div class="meta">
            <div class="label">已使用</div>
            <div class="value">{{ stats.totalUsed }}</div>
          </div>
        </div>
        <div class="card stat slide-up" style="animation-delay: 0.4s">
          <div class="icon" style="background: var(--warning)">⏰</div>
          <div class="meta">
            <div class="label">已过期</div>
            <div class="value">{{ stats.totalExpired }}</div>
          </div>
        </div>
        <div class="card stat slide-up" style="animation-delay: 0.5s">
          <div class="icon" style="background: var(--info)">💰</div>
          <div class="meta">
            <div class="label">优惠金额</div>
            <div class="value">{{ formatMoney(stats.totalDiscount) }}</div>
          </div>
        </div>
      </div>

      <!-- 标签页 -->
      <div class="card slide-up" style="animation-delay: 0.6s">
        <div class="tabs">
          <button 
            class="tab" 
            :class="{ active: activeTab === 'instances' }"
            @click="activeTab = 'instances'"
          >
            用户实例
          </button>
          <button 
            class="tab" 
            :class="{ active: activeTab === 'records' }"
            @click="activeTab = 'records'"
          >
            消费记录
          </button>
        </div>

        <!-- 用户实例标签页 -->
        <div v-if="activeTab === 'instances'" class="tab-content">
          <div class="table-header">
            <h4>用户优惠券实例</h4>
            <div class="filters">
              <select v-model="instanceFilters.status" class="input sm" @change="loadInstances">
                <option value="">全部状态</option>
                <option value="1">未使用</option>
                <option value="2">已使用</option>
                <option value="3">已过期</option>
              </select>
              <button class="btn secondary sm" @click="loadInstances">
                <span class="icon">🔄</span>
                刷新
              </button>
            </div>
          </div>

          <div v-if="instancesLoading" class="loading-state">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
          </div>

          <div v-else-if="instances.length === 0" class="empty-state">
            <div class="icon">📋</div>
            <h4>暂无用户实例</h4>
            <p>该模板还没有用户获取优惠券</p>
          </div>

          <div v-else class="table-container">
            <table class="table">
              <thead>
                <tr>
                  <th>用户ID</th>
                  <th>获取时间</th>
                  <th>过期时间</th>
                  <th>状态</th>
                  <th>使用时间</th>
                  <th>订单号</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="instance in instances" :key="instance.id" class="table-row">
                  <td>{{ instance.userId }}</td>
                  <td>{{ formatDate(instance.createdAt) }}</td>
                  <td>{{ formatDate(instance.expiredAt) }}</td>
                  <td>
                    <span class="status-badge" :class="getInstanceStatusClass(instance.status)">
                      {{ getInstanceStatusText(instance.status) }}
                    </span>
                  </td>
                  <td>{{ instance.usedAt ? formatDate(instance.usedAt) : '-' }}</td>
                  <td>{{ instance.orderNumber || '-' }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 实例分页 -->
          <div v-if="instancePagination.total > 0" class="pagination">
            <div class="pagination-info">
              共 {{ instancePagination.total }} 条记录
            </div>
            <div class="pagination-controls">
              <button 
                class="btn secondary sm" 
                :disabled="instancePagination.current <= 1"
                @click="changeInstancePage(instancePagination.current - 1)"
              >
                上一页
              </button>
              <button 
                class="btn secondary sm" 
                :disabled="instancePagination.current >= Math.ceil(instancePagination.total / instancePagination.pageSize)"
                @click="changeInstancePage(instancePagination.current + 1)"
              >
                下一页
              </button>
            </div>
          </div>
        </div>

        <!-- 消费记录标签页 -->
        <div v-if="activeTab === 'records'" class="tab-content">
          <div class="table-header">
            <h4>消费记录</h4>
            <button class="btn secondary sm" @click="loadRecords">
              <span class="icon">🔄</span>
              刷新
            </button>
          </div>

          <div v-if="recordsLoading" class="loading-state">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
          </div>

          <div v-else-if="records.length === 0" class="empty-state">
            <div class="icon">📋</div>
            <h4>暂无消费记录</h4>
            <p>该模板的优惠券还没有被使用</p>
          </div>

          <div v-else class="table-container">
            <table class="table">
              <thead>
                <tr>
                  <th>用户ID</th>
                  <th>订单号</th>
                  <th>消费时间</th>
                  <th>优惠金额</th>
                  <th>订单金额</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="record in records" :key="record.id" class="table-row">
                  <td>{{ record.userId }}</td>
                  <td>{{ record.orderNumber }}</td>
                  <td>{{ formatDate(record.consumedAt) }}</td>
                  <td class="discount-value">{{ formatMoney(record.discountAmount) }}</td>
                  <td>{{ record.orderAmount ? formatMoney(record.orderAmount) : '-' }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 记录分页 -->
          <div v-if="recordPagination.total > 0" class="pagination">
            <div class="pagination-info">
              共 {{ recordPagination.total }} 条记录
            </div>
            <div class="pagination-controls">
              <button 
                class="btn secondary sm" 
                :disabled="recordPagination.current <= 1"
                @click="changeRecordPage(recordPagination.current - 1)"
              >
                上一页
              </button>
              <button 
                class="btn secondary sm" 
                :disabled="recordPagination.current >= Math.ceil(recordPagination.total / recordPagination.pageSize)"
                @click="changeRecordPage(recordPagination.current + 1)"
              >
                下一页
              </button>
            </div>
          </div>
        </div>


      </div>
    </div>




  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { 
  CouponService, 
  type CouponTemplate,
  type CouponInstance,
  type CouponConsumptionRecord,
  CouponType,
  formatCouponAmount,
  formatCouponDiscount,
  getCouponTypeText
} from '../services/coupon'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const instancesLoading = ref(false)
const recordsLoading = ref(false)

const template = ref<CouponTemplate | null>(null)
const instances = ref<CouponInstance[]>([])
const records = ref<CouponConsumptionRecord[]>([])

const activeTab = ref('instances')

// 统计数据
const stats = reactive({
  totalIssued: 0,
  totalUsed: 0,
  totalExpired: 0,
  totalDiscount: 0
})

// 筛选条件
const instanceFilters = reactive({
  status: '',
  userId: '',
  pageIndex: 1,
  pageSize: 10
})

// 分页信息
const instancePagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const recordPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})



// 生命周期
onMounted(() => {
  const templateId = route.params.id as string
  if (templateId) {
    loadTemplateDetail(templateId)
    loadInstances()
  }
})

// 方法
async function loadTemplateDetail(id: string) {
  loading.value = true
  try {
    const result = await CouponService.getTemplateDetail(id)
    if (result.code === 0 && result.data) {
      template.value = result.data
    } else {
      console.error('加载模板详情失败:', result.message)
    }
  } catch (error) {
    console.error('加载模板详情出错:', error)
  } finally {
    loading.value = false
  }
}

async function loadInstances() {
  if (!template.value?.id) return
  
  instancesLoading.value = true
  try {
    const params = {
      couponTemplateId: template.value.id,
      status: instanceFilters.status ? parseInt(instanceFilters.status) : undefined,
      userId: instanceFilters.userId || undefined,
      pageIndex: instancePagination.current,
      pageSize: instancePagination.pageSize
    }
    
    const result = await CouponService.getCouponInstanceList(params.pageIndex, params.pageSize, template.value?.id, params.userId, params.status)
    if (result.code === 0 && result.data) {
      instances.value = result.data.items
      instancePagination.total = result.data.total
    } else {
      console.error('加载用户实例失败:', result.message)
      instances.value = []
      instancePagination.total = 0
    }
  } catch (error) {
    console.error('加载用户实例出错:', error)
    instances.value = []
    instancePagination.total = 0
  } finally {
    instancesLoading.value = false
  }
}

async function loadRecords() {
  if (!template.value?.id) return
  
  recordsLoading.value = true
  try {
    const params = {
      couponTemplateId: template.value.id,
      pageIndex: recordPagination.current,
      pageSize: recordPagination.pageSize
    }
    
    const result = await CouponService.getCouponConsumptionRecords(params.pageIndex, params.pageSize)
    if (result.code === 0 && result.data) {
      records.value = result.data.items
      recordPagination.total = result.data.total
    } else {
      console.error('加载消费记录失败:', result.message)
      records.value = []
      recordPagination.total = 0
    }
  } catch (error) {
    console.error('加载消费记录出错:', error)
    records.value = []
    recordPagination.total = 0
  } finally {
    recordsLoading.value = false
  }
}



function changeInstancePage(page: number) {
  instancePagination.current = page
  loadInstances()
}

function changeRecordPage(page: number) {
  recordPagination.current = page
  loadRecords()
}

function editTemplate() {
  if (template.value?.id) {
    router.push(`/coupons/edit/${template.value.id}`)
  }
}



// 工具函数
function formatMoney(amount: number): string {
  return `¥${(amount / 100).toFixed(2)}`
}

function formatCouponValue(template: CouponTemplate): string {
  if (template.couponType === CouponType.REDUCTION && template.discountAmount) {
    return formatCouponAmount(template.discountAmount)
  } else if (template.couponType === CouponType.DISCOUNT && template.discount) {
    return formatCouponDiscount(template.discount)
  }
  return '-'
}

function formatDate(dateStr?: string): string {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

function getCouponTypeBadgeClass(type: number): string {
  return type === CouponType.REDUCTION ? 'reduction' : 'discount'
}

function getInventoryClass(inventory?: number): string {
  if (!inventory || inventory <= 0) return 'empty'
  if (inventory <= 10) return 'low'
  return 'normal'
}

function getInstanceStatusClass(status: number): string {
  switch (status) {
    case 1: return 'unused'
    case 2: return 'used'
    case 3: return 'expired'
    default: return 'unknown'
  }
}

function getInstanceStatusText(status: number): string {
  switch (status) {
    case 1: return '未使用'
    case 2: return '已使用'
    case 3: return '已过期'
    default: return '未知'
  }
}


</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  gap: var(--space-6);
  padding: var(--space-4);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--space-4);
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  font-size: var(--text-sm);
}

.breadcrumb-link {
  color: var(--primary);
  text-decoration: none;
}

.breadcrumb-link:hover {
  text-decoration: underline;
}

.breadcrumb-separator {
  color: var(--text-muted);
}

.breadcrumb-current {
  color: var(--text);
  font-weight: 500;
}

.actions {
  display: flex;
  gap: var(--space-3);
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: var(--space-2);
  padding: var(--space-3) var(--space-4);
  border: none;
  border-radius: var(--radius);
  font-size: var(--text-sm);
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  text-decoration: none;
}

.btn.primary {
  background: var(--primary);
  color: white;
}

.btn.primary:hover {
  background: var(--primary-600);
  transform: translateY(-1px);
}

.btn.secondary {
  background: var(--bg-secondary);
  color: var(--text-secondary);
  border: 1px solid var(--border);
}

.btn.secondary:hover {
  background: var(--card-hover);
  color: var(--text);
}

.btn.sm {
  padding: var(--space-2) var(--space-3);
  font-size: var(--text-xs);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
}

.loading-state, .error-state, .empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--space-12);
  text-align: center;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--border);
  border-top: 3px solid var(--primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: var(--space-4);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-state .icon, .empty-state .icon {
  font-size: 48px;
  margin-bottom: var(--space-4);
  opacity: 0.5;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-4);
}

.template-info {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--space-4);
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
}

.info-item label {
  font-size: var(--text-xs);
  font-weight: 500;
  color: var(--text-muted);
  text-transform: uppercase;
}

.info-item .value {
  font-size: var(--text-sm);
  color: var(--text);
}

.description {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

.description label {
  font-size: var(--text-xs);
  font-weight: 500;
  color: var(--text-muted);
  text-transform: uppercase;
}

.description .value {
  font-size: var(--text-sm);
  color: var(--text);
  line-height: 1.5;
}

.stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--space-4);
}

.stat {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  padding: var(--space-4);
}

.stat .icon {
  width: 48px;
  height: 48px;
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat .meta {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
}

.stat .label {
  font-size: var(--text-xs);
  color: var(--text-muted);
  font-weight: 500;
}

.stat .value {
  font-size: var(--text-lg);
  font-weight: 600;
  color: var(--text);
}

.tabs {
  display: flex;
  border-bottom: 1px solid var(--border);
  margin-bottom: var(--space-4);
}

.tab {
  padding: var(--space-3) var(--space-4);
  border: none;
  background: transparent;
  color: var(--text-muted);
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.2s ease;
}

.tab:hover {
  color: var(--text);
}

.tab.active {
  color: var(--primary);
  border-bottom-color: var(--primary);
}

.tab-content {
  min-height: 400px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-4);
}

.table-header h4 {
  margin: 0;
  font-size: var(--text-base);
  font-weight: 600;
}

.filters {
  display: flex;
  gap: var(--space-2);
  align-items: center;
}

.input {
  padding: var(--space-2) var(--space-3);
  border: 1px solid var(--border);
  border-radius: var(--radius);
  font-size: var(--text-sm);
  transition: border-color 0.2s ease;
}

.input:focus {
  outline: none;
  border-color: var(--primary);
}

.input.sm {
  padding: var(--space-1) var(--space-2);
  font-size: var(--text-xs);
}

.textarea {
  resize: vertical;
  min-height: 80px;
}

.table-container {
  overflow-x: auto;
}

.table {
  width: 100%;
  border-collapse: collapse;
  font-size: var(--text-sm);
}

.table th,
.table td {
  padding: var(--space-3);
  text-align: left;
  border-bottom: 1px solid var(--border-light);
}

.table th {
  font-weight: 600;
  color: var(--text-secondary);
  background: var(--bg-secondary);
}

.table-row:hover {
  background: var(--bg-secondary);
}

.badge {
  display: inline-block;
  padding: var(--space-1) var(--space-2);
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);
  font-weight: 500;
}

.badge.reduction {
  background: var(--success-bg);
  color: var(--success);
}

.badge.discount {
  background: var(--info-bg);
  color: var(--info);
}

.status-badge {
  display: inline-block;
  padding: var(--space-1) var(--space-2);
  border-radius: var(--radius-sm);
  font-size: var(--text-xs);
  font-weight: 500;
}

.status-badge.active {
  background: var(--success-bg);
  color: var(--success);
}

.status-badge.inactive {
  background: var(--danger-bg);
  color: var(--danger);
}

.status-badge.unused {
  background: var(--info-bg);
  color: var(--info);
}

.status-badge.used {
  background: var(--success-bg);
  color: var(--success);
}

.status-badge.expired {
  background: var(--warning-bg);
  color: var(--warning);
}

.status-badge.unknown {
  background: var(--bg-secondary);
  color: var(--text-muted);
}

.discount-value {
  font-weight: 600;
  color: var(--primary);
}

.inventory.empty {
  color: var(--danger);
  font-weight: 500;
}

.inventory.low {
  color: var(--warning);
  font-weight: 500;
}

.inventory.normal {
  color: var(--success);
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: var(--space-4);
  padding-top: var(--space-4);
  border-top: 1px solid var(--border-light);
}

.pagination-info {
  font-size: var(--text-sm);
  color: var(--text-muted);
}

.pagination-controls {
  display: flex;
  gap: var(--space-2);
}



/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

.modal {
  background: var(--card-bg);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-xl);
  width: 90vw;
  max-width: 500px;
  max-height: 90vh;
  overflow: hidden;
  animation: slideUp 0.3s ease;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-6);
  border-bottom: 1px solid var(--border);
}

.modal-header h3 {
  margin: 0;
  font-size: var(--text-lg);
  font-weight: 600;
}

.btn-close {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  border-radius: var(--radius);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: var(--text-lg);
  color: var(--text-muted);
}

.btn-close:hover {
  background: var(--bg-secondary);
  color: var(--text);
}

.modal-body {
  padding: var(--space-6);
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}

.field {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
  margin-bottom: var(--space-4);
}

.field label {
  font-size: var(--text-sm);
  font-weight: 500;
  color: var(--text-secondary);
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: var(--space-3);
  margin-top: var(--space-6);
  padding-top: var(--space-4);
  border-top: 1px solid var(--border-light);
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { 
    opacity: 0;
    transform: translateY(20px);
  }
  to { 
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .info-grid {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
  
  .stats {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
}

@media (max-width: 768px) {
  .container {
    padding: var(--space-2);
    gap: var(--space-4);
  }
  
  .header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .stats {
    grid-template-columns: 1fr;
  }
  
  .table-container {
    font-size: var(--text-xs);
  }
  
  .table th,
  .table td {
    padding: var(--space-2);
  }
  
  .packages-grid {
    grid-template-columns: 1fr;
  }
  
  .modal {
    width: 95vw;
    margin: var(--space-4);
  }
  
  .modal-body {
    padding: var(--space-4);
  }
}
</style>